package com.atguigu.spzx.manager.manager;

import com.atguigu.spzx.common.utils.BeanUtils;
import com.atguigu.spzx.common.constant.SysMenuTypeEnum;
import com.atguigu.spzx.common.constant.SysUserStatusEnum;
import com.atguigu.spzx.manager.mapper.SysMenuMapper;
import com.atguigu.spzx.manager.vo.index.RouterVo;
import com.atguigu.spzx.manager.vo.sysMenu.SysMenuQueryTreeVo;
import com.atguigu.spzx.manager.entity.SysMenu;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * PermissionServiceImpl
 * </p>
 *
 * @author flyduck
 * @since 2023/11/2
 */
@Service
public class PermissionManager {

    @Autowired
    private SysMenuMapper sysMenuMapper;

    /**
     * 根据userId获取菜单权限
     * @param userId
     * @return
     */
    public List<RouterVo> getRouterVoListByUserId(Long userId) {
        //根据用户id查询菜单
        List<SysMenu> sysMenuList = getMenuListByUserId(userId);

        //构建树形结构
        List<SysMenuQueryTreeVo> treeRespVos = BeanUtils.toBeanList(sysMenuList, SysMenuQueryTreeVo.class);
        List<SysMenuQueryTreeVo> treeList = com.atguigu.spzx.manager.modules.utils.MenuHelper.buildTree(treeRespVos);

        //转化为前端路由的格式
        List<RouterVo> routerVoList = com.atguigu.spzx.manager.modules.utils.RouterHelper.buildRouters(treeList);
        return routerVoList;
    }

    /**
     * 根据用户id查询菜单
     * @param userId
     * @return
     */
    public List<SysMenu> getMenuListByUserId(Long userId) {
        if (1 == userId) {
            //如果用户id为1，查询所有权限数据
            return sysMenuMapper.getMenuListByStatus(SysUserStatusEnum.NORMAL.getCode());
        }else {
            //如果用户id不是1，根据用户id查询菜单权限
            return sysMenuMapper.getMenuListByUserId(userId);
        }
    }

    /**
     * 根据userId获取按钮权限
     * @param userId
     * @return
     */
    public List<String> getUserPermsListByUserId(Long userId) {
        //根据用户id查询菜单
        List<SysMenu> sysMenuList = getMenuListByUserId(userId);

        List<String> permissionList = sysMenuList.stream()
                .filter(sysMenu -> SysMenuTypeEnum.BUTTON.getCode().equals(sysMenu.getType()))
                .map(SysMenu::getPerms)
                .collect(Collectors.toList());

        return permissionList;
    }
}
